var orderTableUpdate;
var nEditing;
var map = {};// 记录原始的规格数据
var deleteflg = false;
var goodsSkuMapForTab = {};
var orderSkuindex = 0;
/**
 * 页面初始化
 */
$(function() {
    // 保存
    $("#btnOrderSkuSave").click(function() {
        var arrSku = new Array();
        // 表值同步
        if (nEditing != null) {
            saveRow(orderTableUpdate, nEditing);
        }
        nEditing = null;
        var flg = '0';
        $('#orderTableUpdate tbody tr').each(function() {
            var sku = new Object();
            var aData = orderTableUpdate.fnGetData(this);
            if (aData == null) {
                return;
            }

            var temp = aData[19].split("orderSkuId=");
            var orderSkuId = temp.length > 1 ? temp[1].split(" rowIndex", 1) : "";
            orderSkuId = orderSkuId.toString().replace(/\"/g, "");
            if (flg == '0' && aData[0] != "赠" && (aData[19] == "" || (aData[19].indexOf("删除") != -1 && aData[19].indexOf("已删除") == -1))) {
                flg = '1';
            }
            // 新追加的
            if (orderSkuId == "" && aData[19] != "") {
                // 非空白，非删除的时候
                if (aData[7] != null && aData[7] != "" && aData[7] != undefined && aData[19].indexOf("恢复") < 0) {
                    sku.action = "insert";
                    sku.orderId = $('#myid', window.parent.document).val();
                    if ("赠" == aData[0]) {
                        sku.isGift = "y";
                        sku.isVirt = "n";
                    } else if ("虚" == aData[0]) {
                        sku.isVirt = "y";
                        sku.isGift = "n";
                    } else {
                        sku.isVirt = "n";
                        sku.isGift = "n";
                    }
                    var index = aData[7].split("|")[1];
                    index = index != undefined ? index.split(":")[1] : "";
                    if (index != "") {
                        sku.goodsId = goodsSkuMapForTab[index].goodsId;
                        sku.goodsCode = goodsSkuMapForTab[index].goodsCode;
                        sku.goodsName = goodsSkuMapForTab[index].goodsName;
                        sku.skuId = goodsSkuMapForTab[index].skuId;
                        sku.skuCode = goodsSkuMapForTab[index].skuCode;
                        sku.skuName = goodsSkuMapForTab[index].skuName;
                    }
                    sku.qty = aData[9];
                    sku.shippingQty = aData[11];
                    sku.shipedQty = aData[12];
                    sku.price = aData[13];
                    sku.goodsSkuCost = aData[14];
                    sku.factUnitPrice = aData[15];
                    sku.divideOrderFee = aData[17];
                    sku.remark = aData[18];
                    arrSku.push(sku);
                }
            } else {
                var skuValue = map[orderSkuId];
                // 非删除的场合
                if (aData[19].indexOf("恢复") < 0 && aData[19].indexOf("href") != -1) {
                    if (skuValue !== aData[7] + "," + aData[9] + "," + aData[16] + "," + aData[18] + ",n") {
                        sku.action = "update";
                        sku.orderId = $('#myid', window.parent.document).val();
                        if ("赠" == aData[0]) {
                            sku.isGift = "y";
                            sku.isVirt = "n";
                        } else if ("虚" == aData[0]) {
                            sku.isVirt = "y";
                            sku.isGift = "n";
                        } else {
                            sku.isVirt = "n";
                            sku.isGift = "n";
                        }
                        var index = aData[7].split("|")[1];
                        index = index != undefined ? index.split(":")[1] : "";
                        if (index != "") {
                            if (skuValue.split(",")[0] !== aData[7]) {
                                sku.ecSkuId = "";
                                sku.ecItemId = "";
                                sku.ecItemCode = "";
                                sku.ecItemName = "";
                                sku.ecSkuCode = "";
                                sku.ecSkuName = "";
                            }
                            sku.goodsId = goodsSkuMapForTab[index].goodsId;
                            sku.goodsCode = goodsSkuMapForTab[index].goodsCode;
                            sku.goodsName = goodsSkuMapForTab[index].goodsName;
                            sku.skuId = goodsSkuMapForTab[index].skuId;
                            sku.skuCode = goodsSkuMapForTab[index].skuCode;
                            sku.skuName = goodsSkuMapForTab[index].skuName;
                        }
                        sku.qty = aData[9];
                        sku.shippingQty = aData[11];
                        sku.shipedQty = aData[12];
                        sku.price = aData[13];
                        sku.goodsSkuCost = aData[14];
                        sku.factUnitPrice = aData[15];
                        sku.divideOrderFee = aData[17];
                        sku.remark = aData[18];
                        sku.deleted = "n";
                        sku.orderSkuId = orderSkuId;
                        arrSku.push(sku);
                    }
                } else {
                    if (aData[19].indexOf("href") != -1) {
                        if (skuValue !== aData[7] + "," + aData[9] + "," + aData[16] + "," + aData[18] + ",y") {
                            sku.action = "update";
                            sku.orderId = $('#myid', window.parent.document).val();
                            // 因为是删除，所以中间的修改都不变
                            sku.deleted = "y";
                            sku.orderSkuId = orderSkuId;
                            arrSku.push(sku);
                        }
                    }
                }
            }

        });

        //
        if (flg == 0) {
            window.top.window.showModalAlert("必须存在非赠品商品");
        } else {
            // 后台交互
            updateArrSku = arrSku;
            updateSkuQ = "y";
            updateOrderSkus();
        }
    });
    var updateArrSku = null;
    var updateSkuQ = "y";
    function updateOrderSkusQ() {
        updateSkuQ = "n";
        updateOrderSkus();
    }
    function updateOrderSkus() {
        $.ajax({
            type : "POST",
            url : "/order/updateOrderSkus.action?updateSkuQ=" + updateSkuQ,
            data : JSON.stringify(updateArrSku),
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : true, // 同步
            success : function(data) {
                if (data.success == "y") {
                    if (data.qmsg != '' && data.qmsg != null && data.qmsg != undefined) {
                        updateArrSku = new Array();

                        $.each(data.data, function(n, value) {
                            var sku = new Object();
                            sku.action = "update";
                            sku.deleted = value.deleted;
                            sku.orderSkuId = value.orderSkuId;
                            updateArrSku.push(sku);
                        });
                        var reg = new RegExp(/\\n/, "g");
                        window.top.window.showModalConfirmHtml(data.qmsg.replace(reg, "<br/>"), updateOrderSkusQ);
                    } else {
                        window.top.window.showModalAlert("商品数据处理成功");
                        showOrderSkuTab();
                    }

                } else {
                    window.top.window.showModalAlert(data.errormessage);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });

    }

    $('#orderTableUpdate').on('click', 'a.back', function(e) {
        var arrSku = new Array();
        var sku = new Object();
        sku.action = "update";
        sku.deleted = "n";
        sku.orderSkuId = $(this).attr("orderskuid");
        arrSku.push(sku);
        updateArrSku = arrSku;
        updateSkuQ = "y";
        updateOrderSkus();
    });

    var $modalEditItem = $("#modalEditItem");
    
    // 设置规则详情对话框关闭事件发生
    $('#modalEditItem').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    });

    /**
     * 修改商品 中的重置按钮
     */
    $('#btnReset', $modalEditItem).on('click', function() {
        var $modalEditItem = $("#modalEditItem");
        $("#frmSelPrjSku", $modalEditItem)[0].reset();
    });

    /**
     * 修改商品 中的检索按钮
     */
    $('#btnPrjSkuSearch', $modalEditItem).on('click', function() {
        doQuery("radio");
    });

    /**
     * 替换商品画面的确定按钮
     */
    $("#btnAddItem", $modalEditItem).on('click', function(e) {
        e.preventDefault();

        /*
         * 1. 取得当前待更新的记录的ID以及相关表格对象
         * 2. 取得系统商品相关信息
         * 3. 更新商品相关信息
         * 4. 提示更新成功、关闭弹出页面、刷新表格
         */
        var currentOrderSkuId = window.top.window.currentOrderSkuId;
        var currentTable = window.top.window.currentDetailTable;
        
        var notAllowedItem = window.top.window.$("#noAllowedSkuCode").val();
        var notAllowedItemArray = notAllowedItem.split(",");
        
        var orderSkuObj = new Object();
        var selectSku = window.top.window.$('input:radio[name=chkPrjSku]:checked');
        for(var i=0,j=notAllowedItemArray.length;i<j;i++){
            if($(selectSku).attr("skuCode")==notAllowedItemArray[i]){
                window.top.window.showModalAlert("该商品已经存在，不能继续替换");
                return;
            }
        }

        if (selectSku.length <= 0) {
            window.top.window.showModalAlert("请选择商品");
            return false;
        }

        orderSkuObj.orderSkuId = currentOrderSkuId;
        orderSkuObj.goodsId = $(selectSku).attr("goodsId");
        orderSkuObj.goodsCode = $(selectSku).attr("goodsCode");
        orderSkuObj.goodsName = $(selectSku).attr("goodsName");
        orderSkuObj.skuId = $(selectSku).attr("skuId");
        orderSkuObj.skuCode = $(selectSku).attr("skuCode");
        orderSkuObj.skuName = $(selectSku).attr("skuName");
        orderSkuObj.salePrice = $(selectSku).attr("salePrice");
        orderSkuObj.goodsSkuCost = $(selectSku).attr("goodsskucost");

        $.ajax({
            type : "POST",
            url : "/order/updateOrderSkuInfo.action",
            data : JSON.stringify(orderSkuObj),
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : false, // 同步
            success : function(data) {
                if (data.result == "success") {
                    window.top.window.showScoMessage('ok', data.msg);
                    window.top.window.returnCustomModalDialog();
                    $("#btnAddItemClose").click();
                    orderTableUpdate.draw();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    alert(result.errorObject.errorText);
                }
            }
        });
    });

    $("#orderTableUpdate").on('click', 'a.replace', function() {
        
        var nRow = $(this).parents('tr')[0];
        debugger;
        var rowData = orderTableUpdate.row(nRow).data();
        
        var noAllowedSkuCode = $(this).parents("#orderTableUpdate").find("tr:not(:eq(0))").find("td:eq(9)").map(function(){
            return $(this).text();
        }).get().join();

        var $modalEditItem = $("#modalEditItem");
        $("#isGift", $modalEditItem).val("");
        $("#isVirt", $modalEditItem).val(rowData.isVirt);
        $("#modalAddItemTitle", $modalEditItem).html("替换商品");
        
        $("#noAllowedSkuCode", $modalEditItem).val(noAllowedSkuCode);

        window.top.window.currentDetailTable = orderTableUpdate;
        window.top.window.currentOrderSkuId = $(this).attr("orderskuid");

        $('#skuGoodsCode', $modalEditItem).val("");
        $('#skuGoodsName', $modalEditItem).val("");
        $('#skuSkuCode', $modalEditItem).val("");
        $('#skuSkuName', $modalEditItem).val("");

        window.top.window.returnCustomModalDialog();
        var editDialog = window.top.window.borrowCustomModalDialog($modalEditItem);
        editDialog.modal({
            show : true,
            backdrop : 'static'
        });
    });

    $('#orderTableUpdate').on(
            'click',
            'a.delete',
            function(e) {
                var arrSku = new Array();
                var flg = '0';
                var num = 0;
                var sku = new Object();

                if ($(this).parent().parent().children("td:eq(0)").text() != "赠") {
                    $('#orderTableUpdate tbody tr ').each(
                            function() {
                                if ($(this).children('td:eq(' + 22 + ')').text().indexOf("删除") != -1
                                        && $(this).children('td:eq(' + 0 + ')').text() != "赠"
                                        && $(this).children('td:eq(' + 22 + ')').text().indexOf("已删除") == -1) {
                                    num++;
                                }
                            });
                    if (num >= 2) {
                        sku.action = "update";
                        sku.deleted = "y";
                        sku.orderSkuId = $(this).attr("orderskuid");
                        arrSku.push(sku);

                        updateArrSku = arrSku;
                        updateSkuQ = "y";
                        updateOrderSkus();
                    } else {
                        window.top.window.showModalAlert("必须存在非赠品商品");
                    }
                } else {
                    sku.action = "update";
                    sku.deleted = "y";
                    sku.orderSkuId = $(this).attr("orderskuid");
                    arrSku.push(sku);

                    updateArrSku = arrSku;
                    updateSkuQ = "y";
                    updateOrderSkus();
                }

            });
});

/**
 * 查询goodsSku
 * 
 * @returns
 */
function doQuery(selectType) {
    var advData = {
        "goodsCode" : encodeURI(window.top.window.$('#skuGoodsCode').val()),
        "goodsName" : encodeURI(window.top.window.$('#skuGoodsName').val()),
        "skuCode" : encodeURI(window.top.window.$('#skuSkuCode').val()),
        "skuName" : encodeURI(window.top.window.$('#skuSkuName').val()),
        "isGift" : encodeURI(window.top.window.$('#isGift').val()),
        "isVirt" : encodeURI(window.top.window.$('#isVirt').val()),
    };

    var addItemTable = window.top.window.$('#addItemTable').DataTable({
        "bPaginate" : false,
        "bAutoWidth" : true,
        "processing" : true,
        "serverSide" : true,
        "dom" : '<"bottom"rtfli>',
        "searching" : false,
        "deferRender" : true,
        "info" : false,
        "destroy" : true,
        //        "fnDrawCallback": function (oSettings) {
        //            $("#chkAllItem").removeClass("sorting_asc");
        //        },
        "ajax" : {
            "url" : "/stockIn/getPrjSkuListForOrder4ModifySku.action?formJson=" + encodeURI(JSON.stringify(advData)),
        },
        "tableTools" : {
            "sRowSelect" : "bootstrap"
        },
        "columns" : [ {
            "data" : selectType
        }, {
            "data" : "goodsCode"
        }, {
            "data" : "goodsName"
        }, {
            "data" : "skuCode"
        }, {
            "data" : "skuName"
        } ],
        "columnDefs" : [ {
            "orderable" : false,
            "targets" : [ 0 ]
        } ],
        "order" : [ [ 2, "asc" ] ]
    });
}

function showOrderSkuTab() {
    saleData = {};
    giftData = {};
    var tab = $('#tab', window.parent.document).val();

    var shopType = $('#shopTypeHid', window.parent.document).val();

    if (orderTableUpdate == null) {
        orderTableUpdate = $('#orderTableUpdate').DataTable({
            "bPaginate" : false,
            "processing" : true,
            "serverSide" : true,
            "scrollX" : "100%",
            "scrollCollapse" : true,
            "dom" : '<"bottom"rtfli>',
            "searching" : false,
            "deferRender" : true,
            "info" : false,
            "ajax" : {
                "url" : "/order/getOrderSku.action?orderId=" + $('#myid', window.parent.document).val() + "&haveVirt=y"
            },
            "tableTools" : {
                "sRowSelect" : "bootstrap"
            },
            "columns" : [ {
                "data" : "skuProperty"
            }, {
                "data" : "ecItemOuterCode"
            }, {
                "data" : "ecSkuOuterCode"
            }, {
                "data" : "ecItemCode"
            }, {
                "data" : "ecItemName"
            }, {
                "data" : "ecSkuCode"
            }, {
                "data" : "ecSkuName"
            }, {
                "data" : "goodsCode"
            }, {
                "data" : "goodsName"
            }, {
                "data" : "skuCode"
            }, {
                "data" : "skuName"
            }, {
                "data" : "qty"
            }, {
                "data" : "waittingShip"
            }, {
                "data" : "shippingQty"
            }, {
                "data" : "shipedQty"
            }, {
                "data" : "price",
                "render" : numberParser
            }, {
                "data" : "factUnitPrice",
                "render" : numberParser
            }, {
                "data" : "",
                "render" : function(data, type, row, meta) {
                    return parseFloat(row.factUnitPrice * row.qty).toFixed(2);
                }
            }, {
                "data" : "actualPayPrice",
                "render" : numberParser
            }, {
                "data" : "divideOrderFee",
                "render" : numberParser
            }, {
                "data" : "goodsSkuCost",
                "render" : numberParser
            }, {
                "data" : "remark"
            }, {
                "data" : "deleteAction",
                "render" : function(data, type, row, meta) {
                    if ("y" == row.deleted) {
                        if ($('#tab', window.parent.document).val() == "waitVerify") {
                            return row.deleteAction;
                        } else {
                            return '已删除';
                        }
                    } else {
                        if ($('#tab', window.parent.document).val() == "waitVerify" || $('#tab', window.parent.document).val() == "waitAssign") {
                            return row.deleteAction;
                        } else {
                            return '';
                        }
                    }
                }
            },{
                "data": "sn",
                "visible":false,
                "className": "truncate-text tooltip-column-detail"
            }],
            "order" : [ [ 0, "asc" ] ],
            "drawCallback" : function(settings) {
                $("#orderTableUpdate tbody").find("tr").each(function() {
                    for (var i = 0; i < 22; i++) {
                        $(this).children('td:eq(' + i + ')').attr("title", $(this).children('td:eq(' + i + ')').text());
                    }
                });
            }
        }).on('draw.dt', function () {
            // 如果是入库中，就显示SN号页面
            if(window.parent.window.$("li.active:eq(0)").find("a").attr("id")=="shipped" || window.parent.window.$("li.active:eq(0)").find("a").attr("id")=="complete"){
                orderTableUpdate.column(23).visible(true);
            }
            debugger;
            // 文字过长截断显示悬浮框
            $("#orderTableUpdate").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function() {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
        });
        
    } else {
        orderTableUpdate.draw();
    }
}
var numberParser = function(data) {
    var returnValue = "-";
    var numberData = parseFloat(data);
    if (numberData === +numberData) {
        returnValue = numberData.toFixed(2);
    }
    return returnValue;
};